package gptma.bo.services.reporting;

import java.util.Date;
import java.util.Properties;

import javax.annotation.Resource;
import javax.ejb.ActivationConfigProperty;
import javax.ejb.MessageDriven;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.ObjectMessage;
import javax.mail.Address;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.Message.RecipientType;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

// GF bug "MessageDriven cannot be a managed bean"
@MessageDriven(mappedName="jms/GptmaQueue"/*, activationConfig={
    @ActivationConfigProperty(propertyName = "acknowledgeMode", propertyValue = "Auto-acknowledge"),
    @ActivationConfigProperty(propertyName = "destinationType", propertyValue = "javax.jms.Queue")
}*/)
public class ReportingWorker implements MessageListener {

	private static final Logger log = LoggerFactory.getLogger(ReportingOrder.class);

	@Resource(mappedName = "mail/GMailSession")
	private Session session;

	@Override
	public void onMessage(Message msg) {
		try {
			ReportingOrder order = (ReportingOrder) ((ObjectMessage) msg)
					.getObject();

			log.info("Proceeding to reporting generation, order: {}", order);

			javax.mail.Message mail = new MimeMessage(session);
			Address from = new InternetAddress("no-reply@gptma.fr");
			mail.setFrom(from);
			Address to = new InternetAddress("xavier.castel@gmail.com");
			mail.addRecipient(RecipientType.TO, to);
			mail.setSubject("ReportingWorker");
			mail.setSentDate(new Date());
			mail.setText("Report has been sucessfully generated, see attached files. Order: "
					+ order);

			Properties props = session.getProperties();
			String user = props.getProperty("mail.user");
			String password = props.getProperty("mail.gmail.password");

			Transport tr = session.getTransport();
			tr.connect(user, password);

			tr.sendMessage(mail, mail.getAllRecipients());

			tr.close();

			log.info("Reporting generation suceeded");
		} catch (Exception e) {
			log.error("Reporting generation failed: " + e.getMessage(), e);
		}
	}

}
